package com.yulang.security.filter;

import com.yulang.security.properties.CustomSpringSecurityProperties;
import com.yulang.security.controller.CustomController;
import com.yulang.security.exception.ValidateCodeException;
import com.yulang.security.handler.CustomAuthFailureHandler;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ImageCodeValidateFilter extends OncePerRequestFilter {


    @Autowired
    private CustomSpringSecurityProperties properties;


    @Autowired
    private CustomAuthFailureHandler customAuthFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 如果是登录请求就需要校验验证码
        String loginPage = properties.getAuth().getLoginProcessUrl();

        if(loginPage.equals(request.getRequestURI())
                && request.getMethod().equalsIgnoreCase(HttpMethod.POST.name())) {

            try {
                Object attribute = request.getSession().getAttribute(CustomController.SESSION_KEY);
                if(attribute==null) {
                    throw new ValidateCodeException("验证码错误！");
                }
                String code = request.getParameter("code");
                if(StringUtils.isEmpty(code)) {
                    throw new ValidateCodeException("验证码不能为空");
                }

                if(!attribute.toString().equalsIgnoreCase(code)) {
                    throw new ValidateCodeException("验证码错误！");
                }
            }catch (AuthenticationException e){
                // 交给失败处理器进行处理
                customAuthFailureHandler.onAuthenticationFailure(request,response,e);
                return;
            }
        }
        filterChain.doFilter(request,response);
    }
}
